package com.th.cash.th2.main

import android.content.Intent
import androidx.activity.viewModels
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.lxj.xpopup.XPopup
import com.th.basemodel.base.BaseVB2Activity2
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.ext.gotoActivity
import com.th.cash.databinding.ActivityMainBinding
import com.th.cash.storage.LocalSetting
import com.th.cash.th2.splash.DisclosurePopup

//首页
class MainActivity : BaseVB2Activity2<ActivityMainBinding>() {

    private val mViewModel by viewModels<MainVm>()

    override fun getVm(): BaseViewModel {
        return mViewModel
    }

    private val mHomeAdapter by lazy {
        MainScreenAdapter(supportFragmentManager)
    }

    override fun setWindowPadding() {
        ViewCompat.setOnApplyWindowInsetsListener(mBinding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)

        mBinding.mainScreen.currentItem = 0
    }

    override fun init() {
        initTitle()
        initViewPager()
        initBottomNavigation()

        if (!LocalSetting.showDataUpload) {
            showDataUploadPopup()
            LocalSetting.showDataUpload = true
        }
    }

    private fun initTitle() {
//        mBinding.header.headTitle.text = ""
    }

    private fun initViewPager() {
        mBinding.mainScreen.adapter = mHomeAdapter
        mBinding.mainScreen.offscreenPageLimit = 3

        mBinding.mainScreen.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                mBinding.navigationView.setCurrentActiveItem(position)
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
    }

    private fun initBottomNavigation() {
        mBinding.navigationView.setOnTabSelectedListener { position ->
            mBinding.mainScreen.currentItem = position
        }
    }

    fun showHomePage() {
        mBinding.mainScreen.currentItem = 0
    }

    private fun showDataUploadPopup() {
        XPopup.Builder(this)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asCustom(DataUploadPopup(this))
            .show()
    }
}